package net.magicidea;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.AnimationUtils;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ViewFlipper;

public class MainActivity extends Activity implements OnGestureListener {

	private GestureDetector detector;
	private ViewFlipper flipper;
	private int currentMonth = 6;
	LayoutInflater inflater;

	long[] dateWindow;
	OnTouchListener listener;

	private static final String TAG = MainActivity.class.getSimpleName();

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		boolean allowCustomTitle = requestWindowFeature(Window.FEATURE_NO_TITLE);
		
		
		

		// 準備手勢偵測器
		detector = new GestureDetector(this);
		
		listener = new View.OnTouchListener() { 
            public boolean onTouch(View v, MotionEvent event) { 
            	Log.d(TAG, "onTouch");
                if (detector.onTouchEvent(event)) { 
                    return true; 
                } 
                return false; 
            } 
        }; 
		
		
		
		// 準備 LayoutInflater
		inflater = LayoutInflater.from(this);
		
		// 準備 ViewFlipper
		setContentView(R.layout.fliper);
		
		if(allowCustomTitle)
		{
			Log.i(TAG,"allow no title");
//			getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);
		}

		// ---- 準備 flipper 中的預載畫面 ---
		
		// 準備資料查詢時間範圍
		dateWindow = getInitialDateWindow(3);
		flipper = (ViewFlipper) this.findViewById(R.id.ViewFlipper01);

		// 準備預載畫面
		for (int i = 0; i < 3; i++) {
			flipper.addView(createView(dateWindow[i]));
		}

		flipper.setDisplayedChild(1);

	}

	// 產生日期區段用以過濾顯示資料，日期區段為 本期帳單月份 加上 前後各一個月，
	// 若以每月7號為結帳日，今日日期為 7/8，
	// 則本期應顯示 7月份之帳單，整個日期區段 = ｛"六月"、"七月"、"八月"｝
	// 若本日日期為 7/1，則本日仍屬於 6 月之帳目範圍，
	// 日期區段應 = ｛"五月"、"六月"、"七月"｝
	private long[] getInitialDateWindow(int size) {
		Calendar cal = Calendar.getInstance();
		
		int currentMonth = cal.get(Calendar.MONTH); // ex, 7 月
		int currentDay = cal.get(Calendar.DAY_OF_MONTH);
		int currentYear = cal.get(Calendar.YEAR);
		
		int beginMonthForWindow = currentMonth - 1; // ex, window= 6, 7, 8 
		if(currentDay < 8)
		{
			beginMonthForWindow--; // ex, window= 5, 6, 7 
		}
		
		cal.clear();
		cal.set(Calendar.YEAR, currentYear);
		cal.set(Calendar.MONTH, beginMonthForWindow);
		cal.set(Calendar.DAY_OF_MONTH, 8);

		long[] dateWindow = new long[size];

		for (int i = 0; i < size; i++) {
			cal.add(Calendar.MONTH, 1);
			dateWindow[i] = cal.getTimeInMillis();
			Log.d(TAG, cal.getTime().toLocaleString());
		}

		return dateWindow;
	}

	BookDAO dao = BookDAO.getInstance(this);
	SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd hh:mm");
	
	public View createView(long beginTimeForDisplay) {
		LinearLayout root = (LinearLayout) inflater.inflate(R.layout.main, null);
		
		// 設定日期訊息
		TextView view = (TextView) root.findViewById(R.MAIN_ACTIVITY.MONTH_TEXTVIEW);
		Calendar cal = Calendar.getInstance();
		
		cal.setTimeInMillis(beginTimeForDisplay);
		Log.d(TAG,  formatter.format(cal.getTime()) );
		Log.d(TAG, "" +  cal.get(Calendar.MONTH) );
		
		int displayMon = cal.get(Calendar.MONTH)+1;
		view.setText(String.format("%d份消費 ( %d/8 - %d/7 )", displayMon,displayMon,displayMon+1));
		
		
		
		
		
		// 查詢資料庫
		Date begin = cal.getTime();
		
		cal.add(Calendar.MONTH, 1);
		cal.set(Calendar.DAY_OF_MONTH, 7);
		
		Date end = cal.getTime();

		ListView bookItemListView = (ListView) root.findViewById(R.MAIN_ACTIVITY.BOOK_ITEM_LISTVIEW);
		bookItemListView.setOnTouchListener(listener);
		
		MyAdapter adapter = new MyAdapter(this);
		adapter.setItemList(dao.list(begin, end));
		bookItemListView.setAdapter(adapter);

		return root;
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		Log.d(TAG, "onTouch");
		return this.detector.onTouchEvent(event);
	}

	// @Override
	// public boolean onDown(MotionEvent e) {
	// // TODO Auto-generated method stub
	// return false;
	// }

	public boolean onDown(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	/**
	 * 监听滑动
	 */
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		// TODO Auto-generated method stub
		Log.i(TAG, "Fling Happened!");
		if (e1.getX() - e2.getX() > 120) {
			showNext();
			return true;
		} else if (e1.getX() - e2.getX() < -120) {
			showPrevious();
			return true;
		}
		return true;
	}

	private void slideWindow(int monthOffset) {
		Calendar cal = Calendar.getInstance();
		cal.clear();
		
		if(monthOffset > 0)
			Log.d(TAG, "slide forward");
		else
			Log.d(TAG, "slide backward");

		for (int i = 0; i < 3; i++) {
			cal.setTimeInMillis(dateWindow[i]);
			cal.add(Calendar.MONTH, monthOffset);
			dateWindow[i] = cal.getTimeInMillis();
			Log.d(TAG, "" + cal.get(Calendar.MONTH));
		}
	}

	public void showNext() {
		slideWindow(1);
		this.flipper.setInAnimation(AnimationUtils.loadAnimation(this,
				R.anim.push_left_in));
		this.flipper.setOutAnimation(AnimationUtils.loadAnimation(this,
				R.anim.push_left_out));
		this.flipper.setDisplayedChild(2);
		this.flipper.removeViewAt(0);

		MainActivity.this.flipper.addView(createView(dateWindow[2]));

	}

	public void showPrevious() {
		slideWindow(-1);
		this.flipper.setInAnimation(AnimationUtils.loadAnimation(this,
				R.anim.push_right_in));
		this.flipper.setOutAnimation(AnimationUtils.loadAnimation(this,
				R.anim.push_right_out));
		
		this.flipper.setDisplayedChild(0);
		this.flipper.removeViewAt(2);
		this.flipper.addView(createView(dateWindow[0]),0);
	}

	public void onLongPress(MotionEvent e) {
		// TODO Auto-generated method stub

	}

	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		// TODO Auto-generated method stub
		return false;
	}

	public void onShowPress(MotionEvent e) {
		// TODO Auto-generated method stub

	}

	public boolean onSingleTapUp(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}
}

class MyAdapter extends BaseAdapter {
	LayoutInflater inflater;
	Context context;
	BookItem[] itemList;

	public MyAdapter(Context ctx) {
		context = ctx;
		inflater = LayoutInflater.from(context);
	}

	public int getCount() {
		// TODO Auto-generated method stub
		return itemList.length;
	}

	public Object getItem(int idx) {
		// TODO Auto-generated method stub
		return itemList[idx];
	}

	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		
		BookItemView view;
		if(convertView == null)
			view = BookItemView.create(context);
		else
			view = (BookItemView) convertView;

		view.setImage(R.drawable.icon_credit_card);
		view.setAmount(itemList[position].getAmount());
		view.setTime(itemList[position].getBookTime());
		Log.d("test",itemList[position].getBookTime().toLocaleString());
		return view;
	}

	public void setItemList(BookItem[] itemList) {
		this.itemList = itemList;
	}

}